import React from 'react';
import { createRoot } from 'react-dom/client';
import LogViewer from './components/LogViewer';
import SearchBar from './components/SearchBar';
import './styles/logviewer.css';

let root = null;

// 定义全局对象供 Electron 主进程调用
const LogViewerComponentsObj = {
  LogViewer,
  SearchBar,
  renderLogViewer: function(options) {
    const container = document.getElementById('react-log-container');
    if (container) {
      if (!root) {
        root = createRoot(container);
      }
      root.render(
        React.createElement(LogViewer, {
          content: options.content,
          logType: options.logType,
          fileName: options.fileName
        })
      );
    }
  }
};

// 确保覆盖任何现有的LogViewerComponents
window.LogViewerComponents = LogViewerComponentsObj;
console.log('LogViewerComponents已正确初始化:', window.LogViewerComponents);

// 如果页面已经加载完成且存在容器，直接渲染
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeLogViewer);
} else {
  initializeLogViewer();
}

function initializeLogViewer() {
  const container = document.getElementById('react-log-container');
  if (container) {
    // 初始化时不渲染任何内容，等待 renderLogViewer 调用
    console.log('React LogViewer initialized');
  }
}

// 导出为默认导出，供webpack使用
export default window.LogViewerComponents;

export { LogViewer, SearchBar };